import re
import sqlite3
import pymysql

def Linux_rdp_IDS(conn, file_name, file_size):

    f = open("Linux_log/" + file_name, "wb")
    conn.send("准备好接收".encode("utf-8"))  # 确认接收

    received_size = 0

    while received_size < file_size:
        if file_size - received_size > 1024:
            size = 1024
        else:
            size = file_size - received_size  # 最后一次接收

        data = conn.recv(size)  # 多次接收
        data_len = len(data)
        received_size += data_len
        f.write(data)
    f.close()
    conn.send("4".encode("utf-8"))  # 确认接收4
    IP_find = re.compile(r"((1\d{2}|25[0-5]|2[0-4]\d|[1-9]?\d)\.){3}(25[0-5]|2[0-4]\d|1\d{2}|[1-9]?\d)")
    Linux_rdp_iprules = 'TLS connection established'
    Linu_xrdp_loginrules = 'xrdp_wm_log_msg: login failed'
    List_ip = []
    List_cont = []
    List_time = []
    with open("Linux_log/" + file_name, 'r') as f:
        f1 = f.readlines()
        cont = 0
        for i in f1:
            if Linux_rdp_iprules in i:
                IP_time = i.split("]")[0].replace("[", "")
                IP_data = i.split("]")[2]
                ip_search = IP_find.search(i)
                ip_result = ip_search.group()
                List_ip.append(ip_result)  # ip
                List_time.append(IP_time)  # ip时间
                List_cont.append(cont)  # 次数
                cont = 0

                # sqlite_conn = sqlite3.connect("user_information.db")
                # cur = sqlite_conn.cursor()
                # cur.execute('''CREATE TABLE IF NOT EXISTS log_Linux_information(
                #                                                            Linux_time TEXT,
                #                                                            Linux_data TEXT);''')
                # sqlite_conn.commit()
                # cur.execute(f"INSERT INTO log_Linux_information(Linux_time,Linux_data) values('{IP_time}','{IP_data}')")
                # sqlite_conn.commit()
                # sqlite_conn.close()

                db = pymysql.connect(
                    host='localhost',
                    user='root',
                    password='123456',
                    database='maoxuechunqimozuoye'
                )
                py_cursor = db.cursor()
                py_cursor.execute('''CREATE TABLE IF NOT EXISTS log_Linux_information(
                                                                                           Linux_time VARCHAR(256),
                                                                                           Linux_data VARCHAR(256))DEFAULT CHARSET=utf8;''')
                db.commit()
                py_cursor.execute(f"INSERT INTO log_Linux_information(Linux_time,Linux_data) values('{IP_time}','{IP_data}')")
                db.commit()
                db.close()


            if Linu_xrdp_loginrules in i:
                cont = cont + 1
        List_cont.append(cont)

    dic = {}
    for j in List_ip:
        dic[j] = 0

    for i in range(1, len(List_cont)):
        ip = List_ip[i - 1]
        dic[ip] = dic[ip] + List_cont[i]

    difAll = set(List_ip)  # 去重

    for k in difAll:
        flag = 0
        time_num = 0
        for i in range(len(List_ip)):
            if k in List_ip[i] and flag == 0:
                time_num = i
                flag = 1
        db_IP = k
        db_type = '检测到RDP暴力破解'
        db_time = List_time[time_num]
        db_data = "攻击次数:" + str(dic[k])

        # sqlite_conn = sqlite3.connect("user_information.db")
        # cur = sqlite_conn.cursor()
        # cur.execute('''CREATE TABLE IF NOT EXISTS warning_Linux_information(
        #                                                                    Attack_type TEXT,
        #                                                                    Linux_time TEXT,
        #                                                                    Attack_IP TEXT,
        #                                                                    Linux_data TEXT);''')
        # sqlite_conn.commit()
        # cur.execute(
        #     f"INSERT INTO warning_Linux_information(Attack_type,Linux_time,Attack_IP,Linux_data) values('{db_type}','{db_time}','{db_IP}','{db_data}')")
        # sqlite_conn.commit()
        # sqlite_conn.close()
        db = pymysql.connect(
            host='localhost',
            user='root',
            password='123456',
            database='maoxuechunqimozuoye'
        )
        py_cursor = db.cursor()
        py_cursor.execute('''CREATE TABLE IF NOT EXISTS warning_Linux_information(
                #                                                                    Attack_type VARCHAR(256),
                #                                                                    Linux_time VARCHAR(256),
                #                                                                    Attack_IP VARCHAR(256),
                #                                                                    Linux_data VARCHAR(256))DEFAULT;''')
        db.commit()
        py_cursor.execute(
            f"INSERT INTO warning_Linux_information(Attack_type,Linux_time,Attack_IP,Linux_data) values('{db_type}','{db_time}','{db_IP}','{db_data}')")
        db.commit()
        db.close()

